// 当前购物车内容的数据仓库
import {observable, action} from "mobx-miniprogram"
import {getStorage} from '../utils/storage'

const userInfo = getStorage('userInfo') || {}

export const cartStore = observable({
  // 是否展示列表界面的购物车
  show: false,
  // 购物车列表
  cartList: [],
  // 此次是否为外卖
  isSend: false,
  // 店铺对象，默认为用户的默认店铺
  storeObj: (userInfo.defaultstore || {}),
  // 地址对象，默认为用户的默认地址
  addressObj: (userInfo.defaultshippingaddress || {}),

  updateCartList: action(function (cartList) {
    this.cartList = cartList
  }),
  // 修改购物车商品数量
  changeCount: action(function (index, count) {
    if (count === 0) this.deleteCardObj(index)
    else {
      this.cartList[index].count = count
      this.cartList = this.cartList.slice()
    }
  }),

  // 更换购物车开启状态
  changeShow: action(function (show) {
    this.show = show
  }),

  changeIsSend: action(function (isSend) {
    this.isSend = isSend
  }),

  changeStoreObj: action(function (storeObj) {
    this.storeObj = {...storeObj}
  }),
  // 修改购物车
  changeCartList: action(function (cartList) {
    this.cartList = [...cartList]
  }),

  changeAddressObj: action(function (addressObj) {
    this.addressObj = {...addressObj}
  }),

  deleteCardObj: action(function (index) {
    // 移除第index个商品
    this.cartList.splice(index,1)
    this.cartList = this.cartList.slice()
  }),

  // 插入购物车单子
  addCardObj: action(function (cartObj) {
    let flag = true
    this.cartList.forEach(item => {
      // 如果商品类型与其他选择都相同。则直接数量增加
      if (item.id === cartObj.id && item.temp === cartObj.temp) {
        item.count += cartObj.count
        flag = false
      }
    })
    // 否则插入购物车中
    flag && this.cartList.push(cartObj);
    // 需要重新赋值，否则AppData不更新？
    this.cartList = this.cartList.slice()
  }),

  // 清空购物车
  clearCardList: action(function() {
    this.cartList = []
  }),

  // 计算属性。获取当前购物车的总数量
  get allCount() {
    this.cartList.forEach(item => {
      console.log(item);
    })
    return this.cartList.reduce((item, cur) => {
      return item + cur.count
    },0)
  },
  // 计算属性。获取当前购物车的总金额
  get allPrice() {
    return this.cartList.reduce((item, cur) => {
      return cur.count * cur.price + item
    },0)
  },
})